<template>
  <div class="address-form">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="收货人" prop="name">
        <el-input v-model="ruleForm.name" :maxlength="50" :minlength="1"></el-input>
      </el-form-item>
      <el-form-item label="收货地址" prop="province">
        <el-select v-model="ruleForm.province" placeholder="请选择省份">
          <el-option
            :label="province.name"
            :value="province.id"
            :key="province.id"
            v-for="province in region"
          ></el-option>
        </el-select>
        <el-select v-show="city" v-model="ruleForm.city" placeholder="请选择城市" prop="city">
          <el-option
            :label="item.name"
            :value="item.id"
            :key="item.id"
            v-for="item in city"
          ></el-option>
        </el-select>
        <el-select v-show="county" v-model="ruleForm.county" placeholder="请选择区县" prop="county">
          <el-option
            :label="item.name"
            :value="item.id"
            :key="item.id"
            v-for="item in county"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="addition">
        <el-input type="textarea" v-model="ruleForm.addition" :maxlength="80" :minlength="5"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input type="'number" v-model="ruleForm.phone" :maxlength="11" :minlength="11"></el-input>
      </el-form-item>
      <el-form-item class="submit-item">
        <el-button class="submit-btn" type="primary" @click="submitForm('ruleForm')">{{dbId ? '确认修改' : '立即创建'}}
        </el-button>
        <el-button v-if="!isTrue" @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script type="text/ecmascript-6">
  import {ALERT_CUSTOM} from 'base/js/common.config'
  import * as AddressApi from '@/api/address'

  export default {
    props: {
      dbId: {
        type: String,
        default: ''
      },
      returnUrl: {
        type: String,
        default: ''
      }
    },
    data: function () {
      return {
        isTrue: false,
        userDbId: '',
        region: [],
        city: '',
        county: '',
        ruleForm: {
          name: '',
          province: '',
          city: '',
          county: '',
          phone: '',
          addition: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入收货人姓名', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
          ],
          province: [
            {type: 'number', required: true, message: '请选择省份', trigger: 'change'}
          ],
          city: [
            {type: 'number', required: true, message: '请选择城市', trigger: 'change'}
          ],
          county: [
            {type: 'number', required: true, message: '请选择区县', trigger: 'change'}
          ],
          phone: [
            {required: true, message: '请填写手机号', trigger: 'blur'},
            {min: 11, message: '手机号长度为11位', trigger: 'blur'}
          ],
          addition: [
            {required: true, message: '请填写详细地址', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      getCallbackPage: function () {
        let callbackPage = this.returnUrl
        if (!callbackPage) {
          callbackPage = '/center/address.html'
        }
        return callbackPage
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (!valid) {
            return
          }
          let form = this.ruleForm
          let params = {
            passportId: this.userDbId,
            name: form.name,
            mobileCode: form.phone,
            provinceId: form.province,
            cityId: form.city,
            districtId: form.county,
            detail: form.addition,
            isDefault: 'Y'
          }
          if (this.dbId) {
            params.id = this.dbId
          }
          let response = this.dbId ? AddressApi.updateAddress(params) : AddressApi.saveAddress(params)
          response.then((res) => {
            let _self = this
            if (!res) {
              return
            }
            if (res.status !== 1) {
              this.$message({
                showClose: true,
                iconClass: "atrup_Message",
                message: "地址请三级全部选中",
                type: 'success'
              })
              return
            }
            this.$alert(`${this.dbId ? '修改' : '添加'}成功`, '提示', Object.assign(ALERT_CUSTOM, {
              confirmButtonText: '确定',
              callback: function () {
                if (_self.dbId) {
                  localStorage.removeItem(`Address${_self.dbId}`)
                }
                location.href = _self.getCallbackPage()
              }
            }))
          })
        })
      },
      resetForm(formName) {
        location.reload()
//        this.$refs[formName].resetFields()
      },
      fillEditData: function (dbId) {
        let address = sessionStorage[`Address${dbId}`]
        if (!address) {
          // location.href = this.getCallbackPage()
        }
        address = JSON.parse(address)
        this.ruleForm = {
          name: address.name,
          province: address.provinceId,
          city: address.cityId,
          county: address.districtId,
          phone: address.mobileCode,
          addition: address.detail
        }
      },
      _getQueryAllRegion2: function () {
        let allRegion = JSON.parse(localStorage['allRegion'] || '[]')
        if (allRegion.length) {
          this.region = allRegion
          return
        }
        AddressApi.queryAllRegion2({}).then(res => {
          if (res && res.status === 1) {
            this.region = res.data
            localStorage['allRegion'] = JSON.stringify(this.region)
          }
        })
      }
    },
    watch: {
      'ruleForm.province': function (val) {
        for (let i = 0; i < this.region.length; i++) {
          if (val === this.region[i].id) {
            this.city = this.region[i].subregionVo
            return
          }
        }
      },
      'ruleForm.city': function (val) {
        for (let i = 0; i < this.city.length; i++) {
          if (val === this.city[i].id) {
            this.county = this.city[i].subregionVo
            return
          }
        }
      }
    },
    created: function () {
      this._getQueryAllRegion2()
      this.dbId = this.request.dbId
      if (this.dbId) {
        this.fillEditData(this.dbId)
        this.isTrue = true
      }
      this.userDbId = localStorage['userDbId']
      if (!this.userDbId) {
        this.login()
      }
    }
  }
</script>

<style lang="scss" type="text/scss" rel="stylesheet/sass">

  .address-form {
    padding-top: 20px;
    width: 700px;
    .submit-item {
      text-align: center;
    }
    .submit-btn {
      background: #a00912;
      border: 0;
    }
  }

</style>
